package com.example.devices.vm

import androidx.lifecycle.MutableLiveData
import com.blankj.utilcode.util.GsonUtils
import com.example.common.view.vm.BaseViewModel
import com.example.devices.entity.Devices
import com.example.devices.entity.OrderDetail
import com.example.devices.entity.OrderEntity
import com.example.devices.model.DevicesRepository
import com.google.gson.Gson
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import javax.inject.Inject

@HiltViewModel
class DevicesViewModel @Inject constructor(private val repo:DevicesRepository):BaseViewModel() {
    val mSuccess = MutableLiveData<List<Devices>>()
    fun loadDevicesData(){
        mViewModelScope.launch(mDispatcher){
            val (code,data,message) = repo.getDevices()
            if(code == 200){
                mSuccess.postValue(data)
            }else{
                mError.postValue(message)
            }
        }
    }
    val mPostSuccess = MutableLiveData<Devices>()
    fun postDevices(devices:Devices){
        mViewModelScope.launch(mDispatcher){
            val Json = GsonUtils.toJson(devices)
            val (code,data,message)  = repo.postDevices(RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),Json))
            if(code == 200){
                mPostSuccess.postValue(data)
            }else{
                mError.postValue(message)
            }
        }
    }
    val mOrderSuccess = MutableLiveData<List<OrderEntity>>()
    fun orderData(){
        mViewModelScope.launch(mDispatcher){
            val (code,data,message) = repo.getOrder()
            if(code == 200){
                mOrderSuccess.postValue(data)
            }else{
                mError.postValue(message)
            }
        }
    }
    val mOrderDetailSuccess = MutableLiveData<OrderDetail>()
    fun orderDetail(id:Int){
        mViewModelScope.launch(mDispatcher){
            val (code,data,message) = repo.getOrderDetail(id)
            if(code == 200){
                mOrderDetailSuccess.postValue(data)
            }else{
                mError.postValue(message)
            }
        }
    }
    val mInspectionSuccess = MutableLiveData<OrderDetail>()
    fun inspection(id:Int){
        mViewModelScope.launch(mDispatcher){
            val (code,data,message) = repo.inspection(id)
            if(code == 200){
                mInspectionSuccess.postValue(data)
            }else{
                mError.postValue(message)
            }
        }
    }
    val mTransferSuccess = MutableLiveData<OrderDetail>()
    fun transfer(id:Int,inspection:String){
        mViewModelScope.launch(mDispatcher){
            val (code,data,message) = repo.transfer(id,inspection)
            if(code == 200){
                mInspectionSuccess.postValue(data)
            }else{
                mError.postValue(message)
            }
        }
    }
}